/*菜单工具类
* 将后台传过来的字符串转成前端的对象
* 如
* component: "EmpBasic"
* 在前端中应该是
* compoment: EmpBasic*/

//先引入请求
import { getRequest } from "./api";

//定义应该菜单初始化的方法
/*菜单需要格式化 引入router参数 而且还需要往store中保存一下*/
export const initMenu = (router, store) => {
    if (store.state.routes.length > 0) {
        return; //有菜单数据直接return
    }
    //否则
    getRequest("/system/config/menu").then(data => {
        //请求到了数据
        if (data) {
            console.log(data)
            let fmtRoutes = formatRoutes(data)
            //都是使用格式化后的router
            router.addRoutes(fmtRoutes)
            //调用初始化方法initRoutes
            store.commit('initRoutes', fmtRoutes)
            //建立websocket连接
            store.dispatch('connect')
        }
    })
}

//定义formatRoutes方法
export const formatRoutes = (routes) => {
    let fmRoutes = [] //待会要返回的数据
    //先遍历routes
    routes.forEach(router => { //每一项是router
        //定义一些变量 这是一种批量的变量定义 实质上是如 let path = router.path
        let{
            path,
            component,
            name,
            meta,
            iconCls,
            children
        } = router
        //格式化children 如果有children 并且 还是一个数组 有些是没有children 所以需要判断
        if (children && children instanceof Array) {
            //递归调用 格式化
            children = formatRoutes(children)
        }
        //格式化router
        let fmRouter = {
            //此处都是上边的值
            path: path,
            name: name,
            iconCls: iconCls,
            meta: meta,
            children: children,
            //动态获取component
            component(resolve) {
                /* 服务端返回的component 这哩边['../view/' + component + '.vue']拼接成一个完整路径
                 相当于用的时候自动导入这个组件来用*/
                if (component.startsWith("Home")) {
                    require(['../layout/index.vue'], resolve);
                } else if (component.startsWith("Assist")) {
                    require(['../view/assist/' + component + '.vue'], resolve);
                } else if (component.startsWith("Dean")) {
                    require(['../view/dean/' + component + '.vue'], resolve);
                } else if (component.startsWith("Institute")) {
                    require(['../view/institute/' + component + '.vue'], resolve);
                } else if (component.startsWith("Student")) {
                    require(['../view/student/' + component + '.vue'], resolve);
                    /*名前缀字不能与上边相同 否则无法匹配*/
                } else if (component.startsWith("Affair")) {
                    require(['../view/studentAffair/' + component + '.vue'], resolve);
                }else if (component.startsWith("System")) {
                    require(['../view/system/' + component + '.vue'], resolve);
                }else if (component.startsWith("Technology")) {
                    require(['../view/technology/' + component + '.vue'], resolve);
                }
            }
        }
        fmRoutes.push(fmRouter)
    })
    return fmRoutes;
}
